package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Subject;
import service.SubjectService;
import service.impl.SubjectServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author: wyt
 * @date: 2022/12/18 17:12
 */
@WebServlet("/subject/update")
public class SubjectUpdateServlet extends HttpServlet {
    SubjectService subjectService = new SubjectServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //Json转换
        BufferedReader bufferedReader = new BufferedReader(request.getReader());
        String line = null;
        final StringBuilder json = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //接收数据
        Subject subject=new Subject();
        subject.setSname(jsonObject.getString("sname"));
        subject.setPrice(jsonObject.getDouble("price"));
        subject.setDesc(jsonObject.getString("desc"));

        //执行方法存储后返回结果
        JSONObject message=new JSONObject();
        if(subjectService.update(subject)){
            message.put("statue","1");
            message.put("Msg","修改成功");
        }else {
            message.put("statue","0");
            message.put("Msg","修改失败");
        }
        response.getWriter().write(message.toString());

    }
}